﻿using System;
using System.Collections.Generic;
using System.Linq;
using AIMLbot;
using ChatBuddy.Classes.Chat.Helpers;
using ChatBuddy.Classes.Helpers;
using ChatBuddy.Classes.Helpers.Chat;
using ChatBuddy.Classes.Helpers.Friend_Helper;
using ChatBuddy.Classes.Objects;
using CustomUIControls;
using Styx.WoWInternals.WoWObjects;
using Styx;
using System.Windows.Forms;
using Styx.WoWInternals;

namespace ChatBuddy.Classes.Chat.Processor
{
    class ChatHelper
    {

        private static LocalPlayer Me { get { return StyxWoW.Me; } }
        private static Bot _alice;
        private static User _wUser;
        private static Dictionary<string, int> _dictionary;
        private static TaskbarNotifier _notifier;
        public static SettingsHelper SettingsHelper;
        public static List<FriendMember> _friendMembers;
        public static List<FriendMember> _bFriendMembers;
        public static List<GuildMember> _guildMembers; 

        public static void InitializeAlice()
        {
            _dictionary = new Dictionary<string, int>();
            _alice = new Bot();
            _alice.loadSettings();
            _alice.loadAIMLFromFiles();
            _wUser = new User(Me.Name, _alice);
            _notifier = ToastHelper.Toast();

        }

        public static void ChatSay(Styx.CommonBot.Chat.ChatLanguageSpecificEventArgs args)
        {
            var messageTranslate = ConvertMessage(args);

            if (MyNameSaid(messageTranslate))
            {
                var r = new Request(messageTranslate.msg, _wUser, _alice);
                var res = _alice.Chat(r);
            }
        }

        public static void PlayerDied(object sender, LuaEventArgs e)
        {
            
        }

        public static void bn(object sender, LuaEventArgs e)
        {
            foreach (var a in e.Args)
            {
                MessageBox.Show(a.ToString());
            }
        }

        public static void GuildSay(object sender, LuaEventArgs e)
        {
            var helper = new SoundHelper();
            helper.PlaySound("GUILD");

            try
            {
                var message = new GuildSay
                {
                    Message = (string) e.Args[0],
                    Sender = (string) e.Args[1],
                    Language = (string)e.Args[2],
                    ChannelString = (string)e.Args[3],
                    Target = (string)e.Args[4],
                    Flags = (string)e.Args[5],
                    Unknown = (double)e.Args[6],
                    ChannelNumber = (double)e.Args[7],
                    ChannelName = (string)e.Args[8],
                    Unknown2 = (double)e.Args[9],
                    Counter = (double)e.Args[10],
                };

                if (message.Message.ToLower().Contains(Me.Name.ToLower()))
                {
                    if (SettingsHelper.ResponseGuild)
                    {
                        // reply to guild
                        MessageBox.Show(message.Message);
                    }
                }
            }
            catch (Exception er)
            {
                
            }
        }

        public static void ChatWhisper(object sender, LuaEventArgs e)
        {
            var helper = new SoundHelper();
            helper.PlaySound("RANDOM");

            try
            {
                var whisper = new Whisper
                {
                    Message = (string) e.Args[0],
                    Sender = (string) e.Args[1],
                    Language = (string) e.Args[2],
                    ChannelString = (string) e.Args[3],
                    Target = (string) e.Args[4],
                    Flags = (string) e.Args[5],
                    Unknown = (double) e.Args[6],
                    ChannelNumber = (double) e.Args[7],
                    ChannelName = (string) e.Args[8],
                    Unknown2 = (double) e.Args[9],
                    Counter = (double) e.Args[10]
                };

                if (IsGm(whisper.Flags))
                {
                    // a gm private message has been initiated
                    if (SettingsHelper.RespondGm)
                    {
                        
                    }
                }
                else
                {
                    // this message is not from a gm
                    if (!whisper.Sender.ToLower().Contains(Me.Name.ToLower()))
                    {
                        // the user has not sent themselves a PM, allow routine to
                        // continue
                        if (_bFriendMembers.Any(bFriendMember => bFriendMember.Name.ToLower().Contains(whisper.Sender.ToLower())))
                        {
                            // a whisper from a battle net friend
                            if (SettingsHelper.ResponseFriends)
                            {
                                // respond to friend
                                if (_guildMembers.Any(guildMember => guildMember.User.Split('-')[0].ToLower().Contains(whisper.Sender.ToLower())))
                                {
                                    // a whiser from a regular friend
                                    if (SettingsHelper.ResponseGuild)
                                    {
                                        // respond to guild member
                                        MessageBox.Show("Whisper recieved from: " + whisper.Sender.ToLower());
                                    }

                                    return;
                                }

                                return;
                            }
                            return;
                        }

                        if (_friendMembers.Any(friendMember => friendMember.Name.ToLower().Contains(whisper.Sender.ToLower())))
                        {
                            // a whisper from a regular friend
                            if (SettingsHelper.ResponseFriends)
                            {
                                // respond to friend
                                // new RespondFriend().Respond(whisper);
                            }

                            return;
                        }

                        if (_guildMembers.Any(guildMember => guildMember.User.ToLower().Contains(whisper.Sender.ToLower())))
                        {
                            // a whiser from a regular friend
                            if (SettingsHelper.ResponseGuild)
                            {
                                // respond to guild member

                            }
                        }
                    }
                    else
                    {
                        // the user has sent themselves a PM, use following logic to
                        // continue
                        if (CanMessage(whisper.Sender))
                        {
                            Lua.DoString(string.Format("SendChatMessage(\"{0}\", 'WHISPER', nil, \"[CHATBUDDY TEST] {1}\");", AliceResponse(whisper.Message), whisper.Sender));
                        }
                    }
                }
            }
            catch (Exception er)
            {
                MessageBox.Show(er.ToString());
            }
        }

        private static bool CanMessage(string user)
        {
            var foundUser = false;
            var totalMess = 0;

            foreach (var pair in _dictionary.Where(pair => pair.Key == user))
            {
                foundUser = true;
                totalMess = pair.Value;
            }

            if (foundUser)
            {
                totalMess++;
                _dictionary[user] = totalMess;

                if (totalMess == 3)
                {
                    Lua.DoString(string.Format("SendChatMessage(\"{0}\", 'WHISPER', nil, \"{1}\");", "talk to you in a little while, i have some stuff to finish up.", user));
                    return false;
                }

                if (totalMess != 5) return totalMess < 3;

                // ignore the player by adding to block
                // list.
                if (SettingsHelper.HardIgnore)
                {
                    Lua.DoString(string.Format("SendChatMessage(\"{0}\", 'WHISPER', nil, \"{1}\");", "adding you to ignore list, sorry :(", user));

                }
                else
                {
                    Lua.DoString(string.Format("SendChatMessage(\"{0}\", 'WHISPER', nil, \"{1}\");", "sorry real busy, talk to you later, bye", user));
                }

                return false;
            }
            else
            {
                _dictionary.Add(user, 1);
                return true;
            }
        }

        private static string AliceResponse(string message)
        {
            var request = new Request(message, _wUser, _alice);
            return _alice.Chat(request).Output;
        }

        public static void ChatTrade(Styx.CommonBot.Chat.ChatLanguageSpecificEventArgs args)
        {
            var messageTranslate = ConvertMessage(args);

            MessageBox.Show(messageTranslate.auth + " : " + messageTranslate.msg);
        }

        public static void ChatGuild(Styx.CommonBot.Chat.ChatGuildEventArgs args)
        {
            try
            {
                MessageBox.Show(args.Author + " : " + args.Message);
            }
            catch (Exception er)
            {
                MessageBox.Show(er.ToString());
            }
        }

        public static bool IsGm(string tag)
        {
            return tag.ToLower().Contains("gm");
        }

        public static IncomingMessage ConvertMessage(Styx.CommonBot.Chat.ChatLanguageSpecificEventArgs e)
        {
            return new IncomingMessage(e.Message, e.Author, "", "");
        }

        public static bool MyNameSaid(IncomingMessage e)
        {
            if (e.msg.ToLower().Contains(Me.Name.ToLower()))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
